/**
 * 
 */
package com.metagurukul.metaspace.actions;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.metagurukul.metaspace.controller.LoginForm;
import com.metagurukul.metaspace.models.beans.UserLoginDetail;
import com.metagurukul.metaspace.service.UserService;

/**
 * Represents an Action class for user login to the site. This class redirect
 * user to SignUp form for new User. redirect user to home page to regular
 * users.
 * 
 * @author bhagyesh
 * @see Action
 */
public class LoginAction extends Action {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.
	 * ActionMapping, org.apache.struts.action.ActionForm,
	 * javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws SQLException {
		LoginForm loginForm = (LoginForm) form;
		String userName = loginForm.getUserName();
		String password = loginForm.getPassword();

		if (checkValidUserLogin(userName, password)) {
			HttpSession session = request.getSession(true);
			session.setAttribute("user", userName);
			int id = getUserId(userName);
			session.setAttribute("id", id);
			return mapping.findForward("success");
		} else {
			ActionMessages errors = new ActionMessages();
			errors.add("loginErr", new ActionMessage("error.login.invalid"));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}
	}

	/**
	 * Uses UserService class to connect with Dao an get userId
	 * 
	 * @param userName
	 * @return
	 * @throws SQLException
	 */
	private int getUserId(String userName) throws SQLException {
		return UserService.getUserId(userName);
	}

	/**
	 * Validates whether the UserName password are correct or not
	 * 
	 * @param emailId
	 * @param password
	 * @return
	 * @throws SQLException
	 */
	private boolean checkValidUserLogin(String emailId, String password)
			throws SQLException {
		UserLoginDetail userLoginDetail = new UserLoginDetail();
		userLoginDetail.setEmailId(emailId);
		userLoginDetail.setPassword(password);
		return UserService.checkValidUserLogin(userLoginDetail);
	}
}
